package jobs.job3.classloaderdemo.server;

import jobs.job3.classloaderdemo.server.loader.ExecutableTask;
import jobs.job3.classloaderdemo.server.loader.NetworkTaskLoader;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class CalculationNode {
    public CalculationNode(String ip, int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println(ip + ":" + port + " 计算节点启动成功");
        new Thread(() -> {
            int txId = 0; // 事务id
            while (true) {
                txId++;
                try {
                    System.out.println(txId + ".计算节点处于空闲状态，等待分配计算任务...");
                    Socket socket = serverSocket.accept();
                    System.out.println("开始解析计算任务");
                    NetworkTaskLoader networkTaskLoader = new NetworkTaskLoader(socket.getInputStream());
                    ExecutableTask task = networkTaskLoader.receiveTask();
                    task.execute(socket.getOutputStream());
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
